package com.yzjs.service.chainDataInfo.impl;

import com.bsnbase.sdk.client.fabric.FabricClient;
import com.bsnbase.sdk.entity.req.fabric.ReqGetBlockInformation;
import com.bsnbase.sdk.entity.res.fabric.ResGetBlockInformation;
import com.yzjs.common.base.service.BaseServiceImpl;
import com.yzjs.dao.dataInfo.DataInfoMapper;
import com.yzjs.entity.chainDataInfo.ChainDataInfoEntity;
import com.yzjs.dao.chainDataInfo.ChainDataInfoMapper;
import com.yzjs.service.chainDataInfo.ChainDataInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("chainDataInfoService")
public class ChainDataInfoServiceImpl extends BaseServiceImpl<ChainDataInfoEntity, ChainDataInfoMapper> implements ChainDataInfoService {

    @Autowired
    private ChainDataInfoMapper chainDataInfoMapper;
    @Autowired
    private DataInfoMapper dataInfoMapper;

    //根据TxId查询详情
    public void getChainMessage() {
        //获取所有操作成功的记录
        List<ChainDataInfoEntity> chainDataInfoEntities = chainDataInfoMapper.getAll();
        if (chainDataInfoEntities.isEmpty())
            return;
        for (ChainDataInfoEntity entry : chainDataInfoEntities) {
            try {
                ResGetBlockInformation blockInfo = getBlockInfo(entry.getTxId());
                entry.setBlockSize(blockInfo.getBlockSize());
                entry.setPreBlockHash(blockInfo.getPreBlockHash());
                entry.setBlockHash(blockInfo.getBlockHash());
                entry.setBlockNumber(Long.valueOf(blockInfo.getBlockNumber()));
                entry.setStatus(1);
                if (entry.getType() == 0 || entry.getType() == 1) {
                    dataInfoMapper.updateBlockHashByBaseKey(entry.getBaseKey(), entry.getBlockHash());
                }
            } catch (Exception e) {
                e.printStackTrace();
                entry.setStatus(3);
                entry.setRemarks(e.getMessage());
            } finally {
                chainDataInfoMapper.update(entry);
            }
        }
    }

    //获取区块信息
    public ResGetBlockInformation getBlockInfo(String txId) throws Exception {
        FabricClient.initConfig();
        ReqGetBlockInformation rbf = new ReqGetBlockInformation();
        rbf.setTxId(txId);
        ResGetBlockInformation blockInfo = FabricClient.getBlockInfo(rbf);
        return blockInfo;
    }

}